<script lang="ts" setup>
import { ref, reactive, onMounted, h } from 'vue';
import { 
  Card, Table, Button, Input, Space, Form, Select, DatePicker, 
  message, Modal, InputNumber, Tag, Tooltip 
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { 
  getRechargeListApi, 
  createRechargeApi,
  getLandingCompanyOptionsApi,
  type RechargeApi 
} from '#/api/core/recharge';

interface RechargeRecord {
  id: string;
  recharge_id: string;
  recharge_number: string;
  tenant_id: number;
  landing_company: string;
  amount: number;
  bank_name: string;
  bank_account: string;
  status: '充值中' | '充值失败' | '已到账' | '已结清' | '部分退账' | '已退账';
  status_display: string;
  status_description?: string;
  remarks?: string;
  created_at: string;
  updated_at: string;
  arrived_at?: string;
  settled_at?: string;
  refunded_at?: string;
}

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

// 响应式数据
const loading = ref(false);
const dataSource = ref<RechargeRecord[]>([]);

// 搜索表单
const searchForm = reactive({
  recharge_id: '',
  status: undefined as string | undefined,
  landing_company: '',
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
});

// 分页数据
const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 充值弹窗相关
const rechargeModalVisible = ref(false);
const rechargeForm = reactive({
  landing_company_id: undefined as string | number | undefined,
  amount: undefined as number | undefined,
  bank_name: '',
  bank_account: '',
  remarks: ''
});
const rechargeLoading = ref(false);

const landingCompanyOptions = ref<RechargeApi.LandingCompanyOption[]>([]);
const landingCompanyLoading = ref(false);

// 状态选项
const statusOptions = [
  { value: '充值中', label: '充值中' },
  { value: '充值失败', label: '充值失败' },
  { value: '已到账', label: '已到账' },
  { value: '已结清', label: '已结清' },
  { value: '部分退账', label: '部分退账' },
  { value: '已退账', label: '已退账' }
];

// 表格列定义
const columns: TableColumnsType<RechargeRecord> = [
  {
    title: '充值ID',
    dataIndex: 'recharge_id',
    key: 'recharge_id',
    width: 130,
    ellipsis: true,
    customRender: ({ record }) => {
      return h(Tooltip, 
        { title: `完整ID: ${record.id}` }, 
        () => record.recharge_id
      );
    }
  },
  {
    title: '落地公司',
    dataIndex: 'landing_company',
    key: 'landing_company',
    width: 200,
    ellipsis: true,
  },
  {
    title: '充值金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '充值银行名称',
    dataIndex: 'bank_name',
    key: 'bank_name',
    width: 150,
    ellipsis: true,
  },
  {
    title: '充值银行卡号',
    dataIndex: 'bank_account',
    key: 'bank_account',
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => {
      if (!text) return '-';
      // 脱敏处理，显示前4位和后4位
      return text.replace(/(\d{4})\d*(\d{4})/, '$1****$2');
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap: Record<string, string> = {
        '充值中': 'processing',
        '充值失败': 'error',
        '已到账': 'success',
        '已结清': 'default',
        '部分退账': 'warning',
        '已退账': 'default'
      };
      
      return h(Tag, 
        { color: statusColorMap[record.status] }, 
        () => record.status_display
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 160,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString('zh-CN');
    },
  },
];

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: pagination.current,
      per_page: pagination.pageSize,
      recharge_id: searchForm.recharge_id.trim() || undefined,
      status: searchForm.status,
      landing_company: searchForm.landing_company.trim() || undefined,
      start_date: searchForm.start_date,
      end_date: searchForm.end_date,
    };
    
    console.log('📤 发送请求参数:', params);
    
    const response = await getRechargeListApi(params);
    console.log('📥 API响应:', response);
    
    dataSource.value = response.data || [];
    pagination.total = response.total || 0;
    pagination.current = response.current_page || 1;

    console.log('✅ 数据更新成功:', {
      count: dataSource.value.length,
      total: pagination.total,
      current: pagination.current
    });
  } catch (error) {
    console.error('❌ 请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    dataSource.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.recharge_id = '';
  searchForm.status = undefined;
  searchForm.landing_company = '';
  searchForm.start_date = undefined;
  searchForm.end_date = undefined;
  pagination.current = 1;
  fetchData();
};

// 导出数据（占位）
const handleExport = () => {
  message.info('导出功能开发中...');
};

// 分页变化处理
const handleTableChange = (paginationParams: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;
  fetchData();
};

// 时间范围选择处理
const handleDateRangeChange = (dates: any, dateStrings: string[]) => {
  searchForm.start_date = dateStrings[0] || undefined;
  searchForm.end_date = dateStrings[1] || undefined;
};

// 加载落地公司选项
const fetchLandingCompanyOptions = async () => {
  if (landingCompanyOptions.value.length > 0) {
    return;
  }

  try {
    landingCompanyLoading.value = true;
    const response = await getLandingCompanyOptionsApi();
    const options = Array.isArray((response as any)?.data) ? (response as any).data : response;

    landingCompanyOptions.value = (options || [])
      .map((item: RechargeApi.LandingCompanyOption) => {
        const label = item?.label || (item as any)?.name || String(item?.value ?? '');
        const value = item?.value ?? label;
        return {
          ...item,
          label,
          value,
        } as RechargeApi.LandingCompanyOption;
      })
      .filter((item: RechargeApi.LandingCompanyOption) => String(item.value).length > 0 && String(item.label).length > 0);
  } catch (error) {
    console.error('获取落地公司选项失败:', error);
    message.error('获取落地公司列表失败，请稍后重试');
  } finally {
    landingCompanyLoading.value = false;
  }
};

// 打开充值弹窗
const handleOpenRechargeModal = async () => {
  rechargeModalVisible.value = true;
  // 重置表单
  rechargeForm.landing_company_id = undefined;
  rechargeForm.amount = undefined;
  rechargeForm.bank_name = '';
  rechargeForm.bank_account = '';
  rechargeForm.remarks = '';

  if (!landingCompanyOptions.value.length) {
    await fetchLandingCompanyOptions();
  }
};

// 关闭充值弹窗
const handleCloseRechargeModal = () => {
  rechargeModalVisible.value = false;
};

// 提交充值
const handleSubmitRecharge = async () => {
  try {
    // 简单验证
    if (!rechargeForm.landing_company_id) {
      message.error('请选择落地公司');
      return;
    }
    if (!rechargeForm.amount || rechargeForm.amount <= 0) {
      message.error('请输入有效的充值金额');
      return;
    }
    if (!rechargeForm.bank_name.trim()) {
      message.error('请输入充值银行名称');
      return;
    }
    if (!rechargeForm.bank_account.trim()) {
      message.error('请输入充值银行卡号');
      return;
    }

    rechargeLoading.value = true;
    
    const selectedCompany = landingCompanyOptions.value.find((option) => option.value === rechargeForm.landing_company_id);
    if (!selectedCompany) {
      message.error('请选择落地公司');
      return;
    }

    const landingCompanyName = (selectedCompany.label || '').trim();

    const response = await createRechargeApi({
      landing_company: landingCompanyName,
      amount: rechargeForm.amount,
      bank_name: rechargeForm.bank_name.trim(),
      bank_account: rechargeForm.bank_account.trim(),
      remarks: rechargeForm.remarks.trim() || undefined
    });
    
    message.success('充值记录创建成功');
    handleCloseRechargeModal();
    // 刷新列表
    fetchData();
  } catch (error) {
    console.error('创建充值失败:', error);
    message.error('创建充值记录失败，请稍后重试');
  } finally {
    rechargeLoading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="p-5">
    <Card>
      <!-- 搜索区域 -->
      <div class="mb-4">
        <Form layout="inline" :model="searchForm">
          <Form.Item label="充值ID" name="recharge_id">
            <Input
              v-model:value="searchForm.recharge_id"
              placeholder="请输入充值ID"
              style="width: 160px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item label="状态" name="status">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              style="width: 120px"
              allowClear
            >
              <Select.Option 
                v-for="status in statusOptions" 
                :key="status.value" 
                :value="status.value"
              >
                {{ status.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="落地公司" name="landing_company">
            <Input
              v-model:value="searchForm.landing_company"
              placeholder="请输入落地公司"
              style="width: 160px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item label="创建时间" name="date_range">
            <DatePicker.RangePicker
              style="width: 240px"
              @change="handleDateRangeChange"
            />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                @click="handleSearch"
                :loading="loading"
              >
                查询
              </Button>
              <Button @click="handleReset">
                重置
              </Button>
              <Button 
                type="primary" 
                @click="handleOpenRechargeModal"
              >
                充值
              </Button>
              <Button @click="handleExport">
                导出数据
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      
      <!-- 数据表格 -->
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      />
    </Card>

    <!-- 充值弹窗 -->
    <Modal
      v-model:open="rechargeModalVisible"
      title="提交充值"
      :confirmLoading="rechargeLoading"
      @ok="handleSubmitRecharge"
      @cancel="handleCloseRechargeModal"
    >
      <Form :model="rechargeForm" layout="vertical">
        <Form.Item label="落地公司" required>
          <Select
            v-model:value="rechargeForm.landing_company_id"
            placeholder="请选择落地公司"
            :options="landingCompanyOptions"
            :loading="landingCompanyLoading"
            allowClear
            show-search
            optionFilterProp="label"
          />
        </Form.Item>
        
        <Form.Item label="充值金额" required>
          <InputNumber
            v-model:value="rechargeForm.amount"
            placeholder="请输入充值金额"
            style="width: 100%"
            :min="0.01"
            :max="999999999.99"
            :precision="2"
            :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/¥\s?|(,*)/g, '')"
          />
        </Form.Item>
        
        <Form.Item label="充值银行名称" required>
          <Input
            v-model:value="rechargeForm.bank_name"
            placeholder="请输入充值银行名称"
            maxlength="100"
            showCount
          />
        </Form.Item>
        
        <Form.Item label="充值银行卡号" required>
          <Input
            v-model:value="rechargeForm.bank_account"
            placeholder="请输入充值银行卡号"
            maxlength="50"
            showCount
          />
        </Form.Item>
        
        <Form.Item label="备注">
          <Input.TextArea
            v-model:value="rechargeForm.remarks"
            placeholder="请输入备注信息"
            :rows="3"
            maxlength="1000"
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>